<?php

/**
 * Proxy function to quickly define actions available for the view
 *
 * @param	string $action 	The action (e.g. ACTION_SAVE)
 * @param	string $target 	The target (e.g. ACTION_TARGET_OBJECT)
 * @param	string $viewType The type of view (e.g. VIEW_TYPE_API)
 */

function action($action, $target, $viewType, $actionOptions)
{
	// Define the action
	
	$viewAction = array
	(
		'action' => $action,
		'className' => null,
		'isShort' => null,
		'needsConfirmation' => null,
		'object' => null,
		'pathToExtension' => null,
		'target' => $target,
		'viewClass' => VIEW_CLASS_PAGE,
		'viewType' => $viewType
	);
	
	$viewAction = array_merge($viewAction, $actionOptions);
	
	
	// Add the action to the actions for the view
	
	$viewActions = v('::viewActions');
	
	$viewActions[] = $viewAction;
	
	v('::viewActions', $viewActions);
}


/**
 * Proxy function to quickly access to the CApplication singleton
 *
 * @return	CApplication The unique instance of CApplication
 */

function app()
{
	return Loop\CApplication::getInstance();
}


/**
 * Proxy function to quickly get or set a constant
 *
 * @param	string	$constantName	The name of the constant
 * @param	string	$constantValue	The value of the constant (can be null)
 */

function cons($constantName, $constantValue = null)
{
	app()->getConstantManager()->setConstant($constantName, $constantValue);
}


/**
 * Proxy function to quickly define cross-browser CSS properties
 *
 * @return	string
 */

function css($propertyName, $propertyValue = null)
{
	app()->getPlatformManager()->writeStylesheetProperty($propertyName, $propertyValue);
}


/** Proxy function to quickly print something and die
 *
 * @param	mixed	$content	The content to be printed
 */

function d($content = null, $dataType = null, $dataOptions = null)
{
	die(p($content, $dataType, $dataOptions) . "\n");
}


/**
 * Proxy function to quickly access to the database driver
 *
 * @return	IDatabaseDriver the application's database driver
 */

function db($extensionId)
{
	return app()->getDatabaseDriver($extensionId);
}


/**
 * Proxy function to quickly trigger an exception
 * @see CException::__construct
 */

function e($exceptionCode, $exceptionContext = null)
{
	// Dependencies

	require_once(PATH_LOOP . 'Class/CException.php');


	// Create a new exception

	$exception = new Loop\CException($exceptionCode, $exceptionContext);


	// Throw the exception!

	throw $exception;
}


/**
 * Proxy function to quickly get the current environment name
 * @see CPreferenceManager::getEnvironmentName()
 */

function env()
{
	return app()->getPreferenceManager()->getEnvironmentName();
}


/**
 * Proxy function to quickly get a feature
 * @see CFeatureManager::getFeature
 */

function feat($extensionId, $featureName)
{
	return app()->getFeatureManager()->getFeature($extensionId, $featureName);
}


/**
 * Proxy function to quickly find a variable
 * @see CVariableManager::findVariable
 */

function fv($variableName, $isValueRequired = false, $defaultValue = null)
{
	return app()->getVariableManager()->findVariable($variableName, $isValueRequired, $defaultValue);
}


/**
 * Proxy function to quickly create help section
 *
 * @param string $sectionName The name of the section
 * @param array $sectionOptions The given section options
 *
 */

 function help($sectionName, $sectionOptions)
 {
 	app()->getHelpManager()->addSection($sectionName, $sectionOptions);	
 }


/**
 * Redeclare lcfirst() if not PHP 5.3
 */

if (function_exists('lcfirst') == false)
{
	function lcfirst($string)
	{
		$string[0] = strtolower($string[0]);
		
		return $string;
	}
}


/**
 * Proxy function to quickly notify the user
 * @see CNotificationManager::notify
 */

function notify($notificationType, $extensionId, $notificationName, $notificationTarget, $recipientName, $notificationVariables = null, $isAsynchronous = false, $isUnique = false)
{
	app()->getNotificationManager()->notify($notificationType, $extensionId, $notificationName, $notificationTarget, $recipientName, $notificationVariables, $isAsynchronous, $isUnique);
}


/**
 * Proxy function to quickly get the namespace of the current view
 *
 * @param	bool $printResult True to print the result, false to simply return it
 *
 * @return	string The namespace of the current view
 */

function ns($isGlobal = false, $printResult = true)
{
	// Get the view
	
	$view = null;
	
	if ($isGlobal == true)
	{
		$view = view();
	}
	else
	{
		$view = app()->getViewManager()->getCurrentView(); 
	}
	
	
	// Get the namespace
	
	$namespace = null;
	
	if (is_object($view) == true)
	{
		$namespace = $view->getNamespace();
	}
	
	
	// Print or return
	
	if ($printResult == true)
	{
		print $namespace;
	}
	else
	{
		return $namespace;
	}
}


/**
 * Proxy function to quickly share an object or get one
 */

function object($objectName, &$object = null)
{
	if (func_num_args() === 1)
	{
		return app()->getObjectManager()->getSharedObject($objectName);
	}
	else
	{
		app()->getObjectManager()->shareObject($objectName, $object);
	}
}


/**
 * Proxy function to quickly get all shared objects
 */

function objects()
{
	return app()->getObjectManager()->getSharedObjects();
}


/**
 * Proxy function to quickly and safely format data to the output
 *
 * @param	mixed		$data			What needs to be printed
 * @param	string	$dataType		The type of output (optionnal, is detected automatically)
 * @param	array		$dataOptions	An array that contains formatting options related to the data type
 */

function p($data, $dataType = null, $dataOptions = null)
{
	print app()->getStringHelper()->formatData($data, $dataType, $dataOptions);
}


/**
 * Proxy function to quickly ensure a path exists and is valid
 */

function path($pathFragments, $createPath = false, $isSmart = true)
{
	return app()->getFileHelper()->createPath($pathFragments, $createPath, $isSmart);
}


/**
 * Proxy function to quickly log something
 */

function plog($eventMessage, $eventInput = null)
{
	app()->getProfilingManager()->startEvent(PROFILING_TYPE_LOG, $eventMessage, $eventInput);
}


/**
 * Proxy function to quickly access to or define a preference
 *
 * @param	string	$preferenceCategory	The category of the preference (e.g. database, feature, path)
 * @param	string	$preferenceName		The name of the preference to read / write
 * @param	mixed		$preferenceValue	The value of the preference (can be null)
 *
 * @return	mixed The current value of the preference if no value given. Otherwise returns null.
 */

function pref($preferencePath, $preferenceValue = null, $isLocked = false)
{
	if (func_num_args() === 1)
	{
		return app()->getPreferenceManager()->getPreferenceValue($preferencePath);
	}
	else
	{
		app()->getPreferenceManager()->setPreferenceValue($preferencePath, $preferenceValue, $isLocked);
	}
}


/**
 * Proxy function to quickly start a profiling event
 */

function pstart($eventType = null, $eventInput = null)
{
	return app()->getProfilingManager()->startEvent($eventType, null, $eventInput);
}


/**
 * Proxy function to define the current profiling step
 */

function pstep($step)
{
	app()->getProfilingManager()->setStep($step);
}


/**
 * Proxy function to quickly profile a query
 */

function pstop($eventUuid, $eventOutput = null)
{
	app()->getProfilingManager()->stopEvent($eventUuid, $eventOutput);
}


/**
 * Proxy function to quickly execute a SQL query
 *
 * @param	string		$querySql		The SQL query
 * @param	array		$queryVariables	Arguments to be injected into the query
 *
 * @return	mixed The result of the query
 */

function query($driverId, $querySql, &$queryVariables = null, &$finalSql = null)
{
	return app()->getDatabaseDriver($driverId)->executeQuery($querySql, $queryVariables, $finalSql);
}


/**
 * Redirects to or queues a given URL
 *
 * @param	string	$url	The URL to which the user will be redirected
 */

function redirect($url = null)
{
	// Define the URL of redirection if none given
	
	if (empty($url) == true)
	{
		// Do we have a referer?

		$httpReferer = v('SERVER::HTTP_REFERER');
		
		if (empty($httpReferer) == false)
		{
			// Extract the extension, language and URI from the referer

			$url = $httpReferer;
			$pattern = '/^(http.+)(\[[a-zA-Z\-]+\]\/)(' . implode('|', pref('[Loop]/localization/languages')) . ')\/(.*)$/';
			
			if (preg_match($pattern, $url, $matches) === 1)
			{
				// Build the new URL

				$url = root(false);
				
				if (empty($matches[2]) == false)
				{
					$url .= $matches[2];
				}

				$url .= pref('[Loop]/localization/languageIsoCode') . '/';
				$url .= $matches[4];
			}
		}
		else
		{
			// Redirect to the homepage
			
			$url = app()->getPathHelper()->convertPathToUrl(pref('[Loop]/views/pathToPageHome.html'));
		}
	}
	
	
	// Perform the redirection
	
	header('Location: ' . $url);
	die();
}


/**
 * Proxy function to quickly render a view.
 *
 * @param	string	$viewPath		The path to the view (e.g. /Html/Page.Home.html)
 * @param	array	$viewVariables	An array containing variables for the view
 * @param	bool	$printResult	True to print the result, false to simply return it
 *
 * @return	string					In case $printResult is true, will return the rendered view
 */

function render($viewPath, $viewVariables = null, $printResult = true)
{
	// Create the view
	
	$view = app()->getViewManager()->createViewFromPath($viewPath);
	
	
	// Render the view
	
	$viewOutput = app()->getViewManager()->renderView($view, $viewVariables);
	
	
	// Print or return
	
	if ($printResult == true)
	{
		print $viewOutput;
	}
	else
	{
		return $viewOutput;
	}
}


/**
 * Proxy function to quickly get the root URL
 *
 * @param	bool $includeLanguageIsoCode True to append the language ISO code, false otherwise
 *
 * @return	string the root URL
 */

function root($includeLanguageIsoCode = true)
{
	return app()->getPathHelper()->getRootUrl($includeLanguageIsoCode);
}


/**
 * Proxy function to quickly get a translated string with replace part
 *
 * @param	string	$stringName		The name of the string
 * @param	array	$stringReplace	The values for replace
 *
 * @return	string 	$stringValue 	The translated string with the replace values
 */

function rstr($stringName, $stringReplace = array())
{
	$stringValue = str($stringName);

	$stringValue = app()->getStringHelper()->replaceString($stringValue, $stringReplace);

	return $stringValue;
}


/**
 * Proxy function to quickly get or set a translated string
 *
 * @param	string	$stringName		The name of the string
 * @param	string	$stringValue	The value of the string
 *
 * @return	string The translated string if only a name was given, null otherwise
 */

function str($stringName, $stringValue = null)
{
	if (func_num_args() === 1)
	{
		return app()->getStringManager()->getString($stringName);
	}
	else
	{
		app()->getStringManager()->setString($stringName, $stringValue);
	}
}


/**
 * Proxy function to quickly get or set a property type
 *
 * @param	string	$typeName		The name of the type
 * @param	string	$sqlType		The SQL type (e.g. BOOL)
 * @param	string	$pattern		The regular expression defining the pattern
 * @param	string	$fieldType		The field type (e.g. Checkbox)
 * @param	string	$defaultValue	The default value
 * @param	array	$values			The possible values
 */

function type($typeName, $sqlType = null, $pattern = '//', $fieldType = FIELD_TEXT, $defaultValue = null, $values = null)
{
	// Should we get or set the type?

	$constantName = 'TYPE_' . strtoupper($typeName);

	if (empty($sqlType) === true)
	{
		// Get the type

		return json_decode(constant($constantName));
	}
	else
	{
		// Set a new type

		cons
		(
			$constantName,
			json_encode
			(
				array
				(
					'defaultValue' => $defaultValue,
					'fieldType' => $fieldType,
					'pattern' => $pattern,
					'sqlType' => $sqlType,
					'values' => $values
				)
			)
		);
	}
}


/**
 * Proxy function to quickly create a URI from a path
 * @see CStringManager::convertPathToUri
 */

function uri($path)
{
	return app()->getPathHelper()->convertPathToUri($path);
}


/**
 * Proxy function to quickly create an absolute URL
 * @see CStringManager::convertUriToUrl
 */

function url($uri = null, $arguments = null)
{
	return app()->getPathHelper()->convertUriToUrl($uri, $arguments);
}


/**
 * Proxy function to quickly get the current user
 * @see CApplication::getUser() for more information
 */

function user()
{
	return app()->getUser();
}


/**
 * Proxy function to quickly set or get a variable (accessible anywhere)
 * @see CVariableManager::get/setVariable
 */

function v($variablePath, $variableValue = null, $variableOptions = null)
{
	if (func_num_args() == 1)
	{
		return app()->getVariableManager()->getVariable($variablePath);
	}
	else
	{
		return app()->getVariableManager()->setVariable($variablePath, $variableValue, $variableOptions);
	}
}


/**
 * Proxy function to quickly get the root view
 * @see CViewManager::getRootView
 */

function view()
{
	return app()->getViewManager()->getRootView();
}

?>
